﻿@page "/workstations/index"
@attribute [Authorize]


@inject DialogService DialogService
@inject IWorkstationService WorkstationService

<RadzenCard Variant="Variant.Filled" Style="height : 100%;">
    <RadzenStack>
        <SearchFormPartial Model="_searchRequestDto" QueryHandler="QueryHandler"></SearchFormPartial>
        <SearchTablePartial @ref="_requestTable" T="WorkstationInfoResponseDto" ServerData="ServerReload"
                            SearchPartial="_searchPartial" AddHandler="AddHandler" EditHandler="EditHandler">

        </SearchTablePartial>

    </RadzenStack>

</RadzenCard>

@code {
    private WorkstationSearchRequestDto _searchRequestDto = new();
    private IEnumerable<WorkstationInfoResponseDto> _pagedData = new List<WorkstationInfoResponseDto>();
    private SearchPartialInfo _searchPartial = new();
    private SearchTablePartial<WorkstationInfoResponseDto> _requestTable = new();
    private int _totalItems;

    async Task QueryHandler(MouseEventArgs args)
    {
        await _requestTable.ReloadServerData();
    }

    async Task AddHandler(MouseEventArgs args)
    {
        await DialogService.OpenAsync<WorkstationEdit>("Add Workstation", null);
        await _requestTable.ReloadServerData();
    }

    async Task EditHandler(MouseEventArgs args, WorkstationInfoResponseDto model)
    {
        await DialogService.OpenAsync<WorkstationEdit>("Edit Workstation", new Dictionary<string, object> { { "Key", model.Id } });
        await _requestTable.ReloadServerData();
    }

    /// <summary>
    /// Here we simulate getting the paged, filtered and ordered data from the server
    /// </summary>
    private async Task<ODataServiceResult<WorkstationInfoResponseDto>> ServerReload(LoadDataArgs state)
    {
        if (state.Skip != null) _searchRequestDto.Page = (int)(state.Skip + 1);
        if (state.Top != null) _searchRequestDto.Limit = (int)state.Top;
        var result = await WorkstationService.QueryWorkstationsByPage(_searchRequestDto);

        if (result is { Succeeded: true })
        {
            _pagedData = result.Data;
            _totalItems = result.TotalCount;
        }

        return new ODataServiceResult<WorkstationInfoResponseDto>() { Count = _totalItems, Value = _pagedData };
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        //var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

        _searchPartial.IsAdd = true;
        _searchPartial.IsEdit = true;
        _searchPartial.IsDelete = true;
    }


}